package com.markhsiu.minimq.remote.transport.netty;

import java.io.IOException;
import java.util.List;

import com.markhsiu.minimq.message.Message;
import com.markhsiu.minimq.serialize.SerializeCodec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
 
public class MessageObjectDecoder extends ByteToMessageDecoder {

    final public static int MESSAGE_LENGTH = SerializeCodec.MESSAGE_LENGTH;
    private SerializeCodec<Message> codec = null;

    public MessageObjectDecoder(final SerializeCodec<Message> codec) {
        this.codec = codec;
    }

    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    	//出现粘包导致消息头长度不对，直接返回
    	if (in.readableBytes() < MESSAGE_LENGTH) {
            return;
        }

        in.markReaderIndex();
        //读取消息的内容长度
        int messageLength = in.readInt();

        if (messageLength < 0) {
            ctx.close();
        }

        //读到的消息长度和报文头的已知长度不匹配。那就重置一下ByteBuf读索引的位置
        if (in.readableBytes() < messageLength) {
            in.resetReaderIndex();
            return;
        } else {
            byte[] messageBody = new byte[messageLength];
            in.readBytes(messageBody);

            try {
                Message obj = codec.deserialize(messageBody);
                out.add(obj);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
